#include <stdlib.h>
#include <stdio.h>
#include <signal.h> /*for signal() and raise()*/
#include <unistd.h>
#define SIGOFALRM 10
#define SIGOFUSR1 12
#define SIGOFUSR2 14

static void sig_usr(int);
void reload_wpa_supplicant(int channel);
int last_sig_status = -1;
int current_sig_status = -1;
int main() {

	if (signal(SIGALRM, sig_usr) == SIG_ERR) /* deal with differ signal */
		printf("Can't catch SIGALRM\n");

	if (signal(SIGUSR1, sig_usr) == SIG_ERR)
		printf("Can't catch SIGUSR1\n");

	if (signal(SIGUSR2, sig_usr) == SIG_ERR)
		printf("Can't catch SIGUSR2\n");
	
	while (1)
	{
		
	}
}

static void sig_usr(int signo) {
	if (signo == SIGALRM) {
		last_sig_status = current_sig_status;
		current_sig_status = SIGOFALRM;
		reload_wpa_supplicant(1);
		printf("received SIGALRM\n");
		if (current_sig_status != last_sig_status) {/* only differnet signal reload driver */
			printf("received SIGALRM begin init Reconnect 1 channel\n");
			//reload_wpa_supplicant(1);	
		}
	}

	else if (signo == SIGUSR1) {
		last_sig_status = current_sig_status;
		current_sig_status = SIGOFUSR1;
		printf("received SIGUSR1\n");
		reload_wpa_supplicant(7);
		if (current_sig_status != last_sig_status) {
			printf("received SIGUSR1 begin init Reconnect 7 channel\n");
			//reload_wpa_supplicant(7);	
		}
	}

	else if (signo == SIGUSR2) {
		last_sig_status = current_sig_status;
		current_sig_status = SIGOFUSR2;
		printf("received SIGUSR2\n");
		reload_wpa_supplicant(13);
		if (current_sig_status != last_sig_status) {
			printf("received SIGUSR1 begin init Reconnect 13 channel\n");
			//reload_wpa_supplicant(13);	
		}
	}

	else {
		printf("ERROR : received unknow signal %d \n", signo);
	}
}


void reload_wpa_supplicant(int channel) {
	//printf("The status is Disconnected , begin run restart_wpa_supplican...\n");
	system("nice -n -20 killall  wpa_supplicant");
	system("nice -n -20 rmmod xradio_wlan");
	system("nice -n -20 insmod xradio_wlan");
	system("nice -n -20 ifconfig wlan0 192.168.11.2 up");
	if (channel == 1) {
		system("nice -n -20 wpa_supplicant -iwlan0 -c/etc/wifi/wpa_supplicant.conf_1 &");
	}
	else if (channel == 7) {
		system("nice -n -20 wpa_supplicant -iwlan0 -c/etc/wifi/wpa_supplicant.conf_7 &");
	}
	else if (channel == 13) {
		system("nice -n -20 wpa_supplicant -iwlan0 -c/etc/wifi/wpa_supplicant.conf_13 &");
	}
}